//
//  ListLiaisonViewController.m
//  FMS
//
//  Created by Steven on 10/14/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "ListLiaisonViewController.h"
#import "LiaisonDetailViewController.h"
#import "LiaisonBaseLite.h"
#import "UIScrollView+ScrollView.h"

@interface ListLiaisonViewController ()

@end

#define WIDTH_COLUMN_ONE  200
#define WIDTH_COLUMN_TWO  180
#define WIDTH_COLUMN_THREE  220
#define WIDTH_COLUMN_FOUR  200
#define WIDTH_COLUMN_FIVE  160

enum{
    CompanyLiaison_Tag = 5,
    LiaisonType_Tag,
    PersonInChargeLiaison_Tag,
    EmailLiaison_Tag,
    ContactLiaison_Tag,
};

@implementation ListLiaisonViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dictLanguage = [ApplicationDelegate.arrayLanguage objectAtIndex:0];

    }
    return self;
}
- (void)listLiaison{
    isLoadMore = NO;
//    NSMutableArray *array = [LiaisonBaseLite queryLiaisonFrom:indexLiaison numberPage:NUMBER_ROW_PAGE];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *role = [[userDefaults objectForKey:ACCOUNT_ROLE] lowercaseString];
    role = [role lowercaseString];
    NSMutableArray *array = [LiaisonBaseLite queryNewLiaisonByRole:role from:indexLiaison numberPage:NUMBER_ROW_PAGE];
    
    [arrayLiaison addObjectsFromArray:array];
    [self.tbListLiaison reloadData];
    indexLiaison += [array count];
    if ([array count] < NUMBER_ROW_PAGE)
        [self.tbListLiaison hideLoadingMore];
    else
    {
        [self.tbListLiaison showLoadingMore];
        isLoadMore = YES;
    }
    [self.tbListLiaison hideActivity];
    [self showHiddenActivityProgess:NO];
    [btnCurtain removeFromSuperview];
}

- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = YES;
    self.navigationController.navigationBar.translucent = NO;
    [super viewWillAppear:animated];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self addTopBar];
    
    [self addLoadingView];
    
    if (self.navBar) {
        self.navBar.navBarViewDelegate = self;
        [self.navBar.leftButton setBackgroundImage:[UIImage imageNamed:@"btnCancel.png"] forState:UIControlStateNormal];
        
        [self.navBar.rightButton setBackgroundImage:[UIImage imageNamed:@"btnAddNew.png"] forState:UIControlStateNormal];
        
        self.navBar.titleLabel.text = [dictLanguage objectForKey:@"liaison.title-liaison-management"];
    }
    
    [btnFilterBy converCombobox];
    [btnSortBy converCombobox];
    [btnFilterBy setTitle:[dictLanguage objectForKey:@"liaison.title-filter-by"] forState:UIControlStateNormal];
    [btnSortBy setTitle:[dictLanguage objectForKey:@"liaison.title-sort-by"] forState:UIControlStateNormal];
    
    lblTitleCompany.text = [dictLanguage objectForKey:@"liaison.title-company"];
    lblTitleLiaisonType.text = [dictLanguage objectForKey:@"liaison.title-type"];
    lblTitleEmail.text = [dictLanguage objectForKey:@"liaison.title-email"];
    lblTitlePersonInCharge.text = [dictLanguage objectForKey:@"liaison.title-person-in-charge"];
    lblTitleContact.text = [dictLanguage objectForKey:@"liaison.title-contact-number"];
    
    arrayLiaison = [[NSMutableArray alloc] init];
    arraySearchLiaison = [[NSMutableArray alloc] init];
    indexLiaison = 0;
    
    //create a view to prevent touch when init data
    btnCurtain = [UIButton buttonWithType:UIButtonTypeCustom];
    btnCurtain.frame = CGRectMake(0, 0, 1024, 768);
    [btnCurtain setBackgroundColor:[UIColor whiteColor]];
    btnCurtain.alpha = 0.5;
    [btnCurtain addTarget:self action:@selector(doNothing) forControlEvents:UIControlEventTouchUpInside];
    [ApplicationDelegate.tabBarController.view addSubview:btnCurtain];
    
    [self showHiddenActivityProgess:YES];
    [self performSelector:@selector(listLiaison) withObject:self afterDelay:0.5];
    
    seachLiaison.fromView = 2;
    seachLiaison.red    = 1;
    seachLiaison.green  = 128;
    seachLiaison.blue   = 233;
//    seachLiaison.myBackgroundColor = [UIColor colorWithRed:(float)1/255 green:(float)128/255 blue:(float)233/255 alpha:1.0];
}

- (void) doNothing {
    //do nothing
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark process methods

- (void)filterLiaisonByContent:(NSMutableDictionary *)filter{
    isLoadMore = NO;
    
//    NSMutableArray *array = [LiaisonBaseLite filterLiaisonByContactType:[filter objectForKey:@"filterName"] from:indexLiaison numberPage:NUMBER_ROW_PAGE];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *role = [[userDefaults objectForKey:ACCOUNT_ROLE] lowercaseString];
    role = [role lowercaseString];
    NSMutableArray *array = [LiaisonBaseLite filterNewLiaisonByRole:role byContactType:[filter objectForKey:@"filterName"] from:indexLiaison numberPage:NUMBER_ROW_PAGE];
    [arrayLiaison addObjectsFromArray:array];

    [self.tbListLiaison reloadData];
    indexLiaison += [array count];
    if ([array count] < NUMBER_ROW_PAGE)
        [self.tbListLiaison hideLoadingMore];
    else
    {
        [self.tbListLiaison showLoadingMore];
        isLoadMore = YES;
    }
    [self.tbListLiaison hideActivity];
    [self showHiddenActivityProgess:NO];
}

- (void)sortLiaisonByContent:(NSMutableDictionary *)filter{
    NSMutableArray *tmpArray;
    
    if (isSearch)
        tmpArray = arraySearchLiaison;
    else
        tmpArray = arrayLiaison;
    
    [tmpArray sortUsingComparator:^(NSMutableDictionary *obj1, NSMutableDictionary *obj2){
        NSString *content1;
        NSString *content2;
        if ([[filter objectForKey:@"index"] intValue] == COMPANY) {
            content1 = [obj1 objectForKey:@"company"];
            content2 = [obj2 objectForKey:@"company"];
        }
        else if ([[filter objectForKey:@"index"] intValue] == CONTACT_TYPE) {
            if ([[obj1 objectForKey:@"Table"] isEqualToString:kLiaisonDocType])
                content1 = [obj1 objectForKey:@"typeLiaison"];
            else
                content1 = [obj1 objectForKey:@"role"];
            if ([[obj2 objectForKey:@"Table"] isEqualToString:kLiaisonDocType])
                content2 = [obj2 objectForKey:@"typeLiaison"];
            else
                content2 = [obj2 objectForKey:@"role"];
        }
        else if ([[filter objectForKey:@"index"] intValue] == PERSON_IN_CHARGE) {
            if ([[obj1 objectForKey:@"Table"] isEqualToString:kLiaisonDocType])
                content1 = [obj1 objectForKey:@"personInCharge"];
            else
                content1 = [obj1 objectForKey:@"name"];
            if ([[obj1 objectForKey:@"Table"] isEqualToString:kLiaisonDocType])            content2 = [obj2 objectForKey:@"personInCharge"];
            else
                content2 = [obj2 objectForKey:@"name"];
        }
        else{
            if ([[obj1 objectForKey:@"Table"] isEqualToString:kLiaisonDocType])
                content1 = [obj1 objectForKey:@"personInCharge"];
            else
                content1 = [obj1 objectForKey:@"name"];
            if ([[obj1 objectForKey:@"Table"] isEqualToString:kLiaisonDocType])            content2 = [obj2 objectForKey:@"personInCharge"];
            else
                content2 = [obj2 objectForKey:@"name"];
        }
        return [content1 compare:content2 options:NSCaseInsensitiveSearch];
    }];
    [self.tbListLiaison reloadData];
    [self showHiddenActivityProgess:NO];
}

- (void)searchLiaisonByKey:(NSString *)keySearch{
    
//    [arrayLiaison addObjectsFromArray:[LiaisonBaseLite searchLiaisonByKey:keySearch InDatabase:[CouchBaseLiteLib sharedCouchBaseLite].database]];
    isLoadMoreSearch = NO;
    
//    NSMutableArray *array = [LiaisonBaseLite searchLiaisonByKey:keySearch from:indexLiaisonSearch numberPage:NUMBER_ROW_PAGE];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *role = [[userDefaults objectForKey:ACCOUNT_ROLE] lowercaseString];
    role = [role lowercaseString];
    NSMutableArray *array = [LiaisonBaseLite searchNewContactByRole:role byKey:keySearch from:indexLiaisonSearch numberPage:NUMBER_ROW_PAGE];
    [arraySearchLiaison addObjectsFromArray:array];
    [self.tbListLiaison reloadData];
    indexLiaisonSearch += [array count];
    
    if ([array count] < NUMBER_ROW_PAGE)
        [self.tbListLiaison hideLoadingMore];
    else
    {
        [self.tbListLiaison showLoadingMore];
        isLoadMoreSearch = YES;
    }
    if (!isLoadMoreSearch) {
        [self.tbListLiaison hideActivity];
    }
    [self showHiddenActivityProgess:NO];
}
#pragma mark action methods
- (IBAction)filterLiaison:(id)sender {
    [self didmissPopoverController];
    
    UIButton *btnSender = (UIButton *)sender;
    FilterViewController *controller = [[FilterViewController alloc] initWithStyle:UITableViewStylePlain filterType:filter_filter_liaison];
    controller.delegate = self;
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    [popoverController presentPopoverFromRect:btnSender.frame inView:btnSender.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (IBAction)sortLiaison:(id)sender {
    
    [self didmissPopoverController];
    
    UIButton *btnSender = (UIButton *)sender;
    FilterViewController *controller = [[FilterViewController alloc] initWithStyle:UITableViewStylePlain filterType:filter_sort_liaison];
    controller.delegate = self;
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    [popoverController presentPopoverFromRect:btnSender.frame inView:btnSender.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}


#pragma mark - LiaisonDetailView delegate

- (void)didUpdateLiaisonInfo:(NSMutableDictionary *)dictLiaison{
    if ([[dictLiaison objectForKey:@"indexRow"] intValue] < 0) {
        isSearch = NO;
        indexLiaison = 0;
        [arrayLiaison removeAllObjects];
        [self listLiaison];
//        [self.tbListLiaison reloadData];
//        [arrayLiaison addObject:dictLiaison];
//        [self.tbListLiaison insertRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:[arrayLiaison count] - 1 inSection:0], nil] withRowAnimation:UITableViewRowAnimationRight];
    }
    else{
        [self.tbListLiaison reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:[[dictLiaison objectForKey:@"indexRow"] intValue] inSection:0], nil] withRowAnimation:UITableViewRowAnimationMiddle];
    }
}

#pragma mark - NavViewDelegate

- (void)didClickedLeftButton {
    [self.navigationController dismissModalViewControllerAnimated:YES];
}


- (void)didClickedRightButton{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *permissionDict = [userDefaults objectForKey:LIAISON_PERMISSION];
    BOOL isAdd = [[permissionDict objectForKey:@"add"] boolValue];
    if (!isAdd) {
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
        [dialog show];
        return;
    }
    
    LiaisonDetailViewController *controller = [[LiaisonDetailViewController alloc] initWithNibName:@"LiaisonDetailViewController" bundle:[NSBundle mainBundle] statusView:ADD_VIEW];
    controller.delegate = self;
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark tableview datasource

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (isSearch)
        return [arraySearchLiaison count];
    return [arrayLiaison count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellLiaisonInden = @"LiaisonCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellLiaisonInden];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellLiaisonInden];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        
        UILabel *lblCompany = [[UILabel alloc] initWithFrame:CGRectMake(20, 22, WIDTH_COLUMN_ONE, 22)];
        lblCompany.tag = CompanyLiaison_Tag;
        lblCompany.font = [UIFont fontWithName:FMS_REGULAR_FONT size:15];
        lblCompany.textColor = FMS_COLOR_DEFAUL;
        [cell.contentView addSubview:lblCompany];
        
        UILabel *lblType = [[UILabel alloc] initWithFrame:CGRectMake(230, 22, WIDTH_COLUMN_TWO, 22)];
        lblType.tag = LiaisonType_Tag;
        lblType.font = [UIFont fontWithName:FMS_REGULAR_FONT size:15];
        lblType.textColor = FMS_COLOR_DEFAUL;
        [cell.contentView addSubview:lblType];
        
        
        UILabel *lblPersonInCharge = [[UILabel alloc] initWithFrame:CGRectMake(420, 22, WIDTH_COLUMN_THREE, 22)];
        lblPersonInCharge.tag = PersonInChargeLiaison_Tag;
        lblPersonInCharge.font = [UIFont fontWithName:FMS_REGULAR_FONT size:15];
        lblPersonInCharge.textColor = FMS_COLOR_DEFAUL;
        [cell.contentView addSubview:lblPersonInCharge];
        
        UILabel *lblEmail = [[UILabel alloc] initWithFrame:CGRectMake(650, 22, WIDTH_COLUMN_FOUR, 22)];
        lblEmail.tag = EmailLiaison_Tag;
        lblEmail.font = [UIFont fontWithName:FMS_REGULAR_FONT size:15];
        lblEmail.textColor = FMS_COLOR_DEFAUL;
        [cell.contentView addSubview:lblEmail];
        
        UILabel *lblContact = [[UILabel alloc] initWithFrame:CGRectMake(860, 22, WIDTH_COLUMN_FIVE, 22)];
        lblContact.tag = ContactLiaison_Tag;
        lblContact.font = [UIFont fontWithName:FMS_REGULAR_FONT size:15];
        lblContact.textColor = FMS_COLOR_DEFAUL;
        [cell.contentView addSubview:lblContact];
        
    }
    UILabel *lblCompany = (UILabel *)[cell.contentView viewWithTag:CompanyLiaison_Tag];
    UILabel *lblPersonInCharge = (UILabel *)[cell.contentView viewWithTag:PersonInChargeLiaison_Tag];
    UILabel *lblEmail = (UILabel *)[cell.contentView viewWithTag:EmailLiaison_Tag];
    UILabel *lblContact = (UILabel *)[cell.contentView viewWithTag:ContactLiaison_Tag];
    UILabel *lblType = (UILabel *)[cell.contentView viewWithTag:LiaisonType_Tag];
    
    NSMutableDictionary *dict;
    if (isSearch)
        dict = [arraySearchLiaison objectAtIndex:indexPath.row];
    else
        dict = [arrayLiaison objectAtIndex:indexPath.row];
    if ([[dict objectForKey:@"Table"] isEqualToString:kUserDocType]) {
        lblPersonInCharge.text = [dict objectForKey:@"name"];
        lblContact.text = [dict objectForKey:@"phone"];
        lblType.text = [dict objectForKey:@"role"];
    }
    else{
        lblPersonInCharge.text = [dict objectForKey:@"personInCharge"];
        lblContact.text = [dict objectForKey:@"contactNumber"];
        lblType.text = [dict objectForKey:@"typeLiaison"];
    }
    lblCompany.text = [dict objectForKey:@"company"];
    lblEmail.text = [dict objectForKey:@"email"];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    LiaisonDetailViewController *controller = [[LiaisonDetailViewController alloc] initWithNibName:@"LiaisonDetailViewController" bundle:[NSBundle mainBundle] statusView:DETAIL_VIEW];
    controller.delegate = self;
    NSMutableDictionary *dict;
    if (isSearch)
        dict = [arraySearchLiaison objectAtIndex:indexPath.row];
    else
        dict = [arrayLiaison objectAtIndex:indexPath.row];
    controller.dictLiaison = dict;
    [controller.dictLiaison setObject:[NSNumber numberWithInt:indexPath.row] forKey:@"indexRow"];
    [self.navigationController pushViewController:controller animated:YES];
    [controller reloadLiaison];
}

#pragma mark searchbar delegate

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
//    isSearch = YES;
    isLoadMoreSearch = NO;
    
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    if ([searchBar.text length] < 2) {
        isSearch = NO;
        [self.tbListLiaison reloadData];
        return;
    }
    [arraySearchLiaison removeAllObjects];
    indexLiaisonSearch = 0;
    strSearchKey = searchBar.text;
    [self searchLiaisonByKey:searchBar.text];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    if ([searchBar.text length] < 2) {
        isSearch = NO;
        [self.tbListLiaison reloadData];
        return;
    }
    [arraySearchLiaison removeAllObjects];
    indexLiaisonSearch = 0;
    strSearchKey = searchBar.text;
    [self searchLiaisonByKey:searchBar.text];
}

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    isSearch = YES;
//    isLoadMoreSearch = NO;
    
    NSString *textSearch = [searchBar.text stringByReplacingCharactersInRange:range withString:text];
    int lengthSearch = [textSearch length];
    if (lengthSearch > 256)
        return NO;
    
    if (lengthSearch >= 1) {
        NSRange r;
        [arraySearchLiaison removeAllObjects];
        for (int i = 0; i < [arrayLiaison count]; i++) {
            NSMutableDictionary *dict = [arrayLiaison objectAtIndex:i];
            
            if ([[dict objectForKey:@"Table"] isEqualToString:kUserDocType]) {
                r = [[dict objectForKey:@"name"] rangeOfString:textSearch options:NSCaseInsensitiveSearch];
                if (r.location != NSNotFound) {
                    [arraySearchLiaison addObject:dict];
                    continue;
                }
                
                r = [[dict objectForKey:@"phone"] rangeOfString:textSearch options:NSCaseInsensitiveSearch];
                if (r.location != NSNotFound) {
                    [arraySearchLiaison addObject:dict];
                    continue;
                }
            }
            else{
                r = [[dict objectForKey:@"personInCharge"] rangeOfString:textSearch options:NSCaseInsensitiveSearch];
                if (r.location != NSNotFound) {
                    [arraySearchLiaison addObject:dict];
                    continue;
                }
                
                r = [[dict objectForKey:@"contactNumber"] rangeOfString:textSearch options:NSCaseInsensitiveSearch];
                if (r.location != NSNotFound) {
                    [arraySearchLiaison addObject:dict];
                    continue;
                }
            }
            
            r = [[dict objectForKey:@"email"] rangeOfString:textSearch options:NSCaseInsensitiveSearch];
            if (r.location != NSNotFound) {
                [arraySearchLiaison addObject:dict];
                continue;
            }
            
            
        }
        [self.tbListLiaison reloadData];
        [self.tbListLiaison hideActivity];
    }
    return YES;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    isSearch = NO;
    [searchBar resignFirstResponder];
    [self.tbListLiaison reloadData];
}

#pragma mark FilterView delegate

- (void)didSelectFilter:(NSMutableDictionary *)filterDict{
    switch ([[filterDict objectForKey:@"filterType"] intValue]) {
        case filter_filter_liaison:
        {
            [arrayLiaison removeAllObjects];
            [self.tbListLiaison reloadData];
        }
            break;
    }
    
    [self didmissPopoverController];
    [self showHiddenActivityProgess:YES];
    
    [self performSelector:@selector(delayAfterFilter:) withObject:filterDict afterDelay:0.5];
}

- (void) delayAfterFilter:(NSMutableDictionary*)filterDict {
    switch ([[filterDict objectForKey:@"filterType"] intValue]) {
        case filter_filter_liaison:
        {
            [self didmissPopoverController];
            
            contentFitler = filterDict;
            [btnFilterBy setTitle:[filterDict objectForKey:@"filterName"] forState:UIControlStateNormal];

            if (isSearch) {
                [arraySearchLiaison removeAllObjects];
                indexLiaisonSearch = 0;
                if ([[filterDict objectForKey:@"index"] isEqualToString:@"0"]) {
                    [self searchLiaisonByKey:strSearchKey];
                }
                else
                    [self filterSearchedLiaison:filterDict];
            }
            else {
                [arrayLiaison removeAllObjects];
                indexLiaison = 0;
                if ([[filterDict objectForKey:@"index"] isEqualToString:@"0"]) {
                    [self listLiaison];
                }
                else
                    [self filterLiaisonByContent:filterDict];
            }
        }
            break;
        case filter_sort_liaison:
        {
            [self didmissPopoverController];
            
            contentSort = filterDict;
            
            [btnSortBy setTitle:[filterDict objectForKey:@"filterName"] forState:UIControlStateNormal];
            
            [self sortLiaisonByContent:filterDict];
        }
            break;
        default:
            break;
    }
}

- (void) filterSearchedLiaison:(NSMutableDictionary*)filterDict {
    NSString *tmpRole = [filterDict objectForKey:@"filterName"];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *role = [[userDefaults objectForKey:ACCOUNT_ROLE] lowercaseString];
    role = [role lowercaseString];
    
    NSMutableArray *tmpArray = [LiaisonBaseLite searchNewContactByRole:role byKey:strSearchKey andContactType:tmpRole from:indexLiaisonSearch numberPage:NUMBER_ROW_PAGE];
    [arraySearchLiaison addObjectsFromArray:tmpArray];
    
    indexLiaisonSearch += [tmpArray count];
    if ([tmpArray count] < NUMBER_ROW_PAGE)
        [self.tbListLiaison hideLoadingMore];
    else
    {
        [self.tbListLiaison showLoadingMore];
        isLoadMoreSearch = YES;
    }
    
    [self.tbListLiaison reloadData];
    [self showHiddenActivityProgess:NO];
}

#pragma mark scrollview load more
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    didReadyLoadMore = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    float bottomEdge = scrollView.contentOffset.y + scrollView.frame.size.height;
    if (bottomEdge >= scrollView.contentSize.height && !didReadyLoadMore)
    {
        didReadyLoadMore = YES;
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (didReadyLoadMore) {
        if(isSearch)
        {
            if(!isLoadMoreSearch)
                [self.tbListLiaison hideLoadingMore];
            else {
                if ([[contentFitler objectForKey:@"index"] isEqualToString:@"0"])
                    [self searchLiaisonByKey:strSearchKey];
                else
                    [self filterSearchedLiaison:contentFitler];
            }
        }
        else {
            if(!isLoadMore)
            {
                [self.tbListLiaison hideLoadingMore];
                return;
            }
            [self.tbListLiaison showActivity];
            if (contentFitler) {
                switch ([[contentFitler objectForKey:@"filterType"] intValue]) {
                    case filter_filter_liaison:
                    {
                        
                        [self filterLiaisonByContent:contentFitler];
                    }
                        break;
                    case filter_sort_liaison:
                    {
                        [self filterLiaisonByContent:contentFitler];
                        [self sortLiaisonByContent:contentSort];
                    }
                        break;
                    default:
                        break;
                }
            }
            else
                [self listLiaison];
        }
    }
}

- (void)addLoadingView{
    activityView = [[UIActivityIndicatorView alloc] init];
    activityView.frame = CGRectMake(1024/2 - 30.0/2, 768/2 - 30.0/2, 30.0, 30.0);
    activityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    activityView.hidesWhenStopped = YES;
    [self.view addSubview:activityView];
    activityView.hidden = YES;
}

- (void)showHiddenActivityProgess:(BOOL)isYES
{
    activityView.hidden = !isYES;
    if (isYES) {
        [activityView startAnimating];
    }
    else
        [activityView stopAnimating];
    
}

@end
